package com.study.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncCurator {

    private static String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
    private static RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

    private static CountDownLatch latch = new CountDownLatch(2);
    private static ExecutorService executorService = Executors.newScheduledThreadPool(2);
    private static String path= "/zlx";
    private static CuratorFramework client = CuratorFrameworkFactory
            .builder()
            .connectString(connectStr)
            .sessionTimeoutMs(5000)
            .retryPolicy(retryPolicy)
            //指定命名空间
            // .namespace("")
            .build();

    public static void main(String[] args) throws Exception{

        client.start();
        System.out.println("Main thread: " + Thread.currentThread().getName());
        //异步回调函数，会由另一个县城EventThread 进行处理
        client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {
            public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                System.out.println("event [code: " + curatorEvent.getResultCode() + ", type: " + curatorEvent.getType() + "]");
                System.out.println("Thread of processResult :" + Thread.currentThread().getName());
                latch.countDown();
            }
        }, executorService).forPath(path, "init".getBytes());

        client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {
            public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                System.out.println("event [code: " + curatorEvent.getResultCode() + ", type: " + curatorEvent.getType() + "]");
                System.out.println("Thread of processResult :" + Thread.currentThread().getName());
                latch.countDown();
            }
        }, executorService).forPath(path, "init".getBytes());
        latch.await();
        executorService.shutdown();
    }
}
